package auth

import "strings"

/*
将接口中注册的权限处理成权限树
 */
var AccessTree = make(AccessTreeNode)

func RegisterAccess(code string) {
	ns := strings.Split(code, Dot)
	AccessTree = hangStringNode(AccessTree, ns)
}

// 访问项
type AccessTreeNode map[string]AccessTreeNode

func (AccessTreeNode) Append(list ...string) AccessTreeNode {
	tree := make(AccessTreeNode)
	for _, item := range list {
		ns := strings.Split(item, Dot)
		tree = hangStringNode(tree, ns)
	}
	return tree
}

func hangStringNode(tree AccessTreeNode, codes []string) AccessTreeNode {
	l := len(codes)
	if l == 0 {
		panic("codes不能为空")
	} else {
		if tree == nil {
			tree = make(AccessTreeNode)
		}
		node := tree[codes[0]]
		if l > 1 {
			node = hangStringNode(node, codes[1:])
		}
		tree[codes[0]] = node
	}
	return tree
}